<?php

namespace app\logic;

class IdentityCard
{
    private static $obj = null;

    /**
     * 类入口
     * @return IdentityCard|null
     */
    public static function getInstance()
    {
        if (is_null(self::$obj))
            self::$obj = new self();
        return self::$obj;
    }

    /**
     * 阿里云市场检查身份证接口
     * @param string $real_name 真实姓名
     * @param string $id_card 身份证号码
     * @return mixed
     */
    public function aliYunCheckIdCard($real_name, $id_card)
    {
        $host = "http://aliyunverifyidcard.haoservice.com";
        $path = "/idcard/VerifyIdcardv2";
        $method = "GET";
        $appcode = config('aliyun.app_code');
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "cardNo=" . $id_card . "&realName=" . urlencode($real_name);
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $str_info = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Error' . curl_error($curl);
        }
        curl_close($curl);

        $json_info = preg_replace("/.*\r\n/", '', $str_info);
        $arr_info = json_decode($json_info, true);
//        dump($arr_info);
        if (isset($arr_info['error_code']) && $arr_info['error_code'] == 0 && isset($arr_info['result']['isok']) && $arr_info['result']['isok'] === true) {
            return true;
        } else {
            return false;
        }
    }
}
